package com.kl.daojishiii;

import android.annotation.TargetApi;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.Calendar;

@TargetApi(21)
public class JobSchedulerService extends JobService {
    public static long  start_time = 1000;
    private static Boolean jobServiceHave = false;
    public static boolean isJobServiceAlive() {
        return jobServiceHave;
    }
    private static final int JOB_TASK = 10001;
    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            // 执行你想做的工作
            Calendar calendar = Calendar.getInstance();
            long time = calendar.getTimeInMillis();

            Log.d("skl", String.valueOf(time - start_time));
            if(time - start_time > 1000 * 60 * 10){
                Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));

// Play the ringtone
                ringtone.play();
            }
            // 通知系统任务执行结束
            if (Build.VERSION.SDK_INT >= 24) {
                // android7.0及以上使用重新开启一个JobScheduler
                JobSchedulerUtil.getJobSchedulerInstance(JobSchedulerService.this).startJobScheduler();
                jobFinished((JobParameters) msg.obj, true);
            } else {
                // 5.0 6.0
                jobFinished((JobParameters) msg.obj, false);
            }
            return true;
        }
    });


    @Override
    public boolean onStartJob(JobParameters params) {
        jobServiceHave = true;
        // 因为是子线程且jobFinished需要params,通过handler传递
        Message msg = new Message();
        msg.obj = params;
        msg.what = JOB_TASK;
        mHandler.sendMessage(msg);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        mHandler.removeMessages(JOB_TASK);
        return false;
    }




}
